<!--
 * @Author: 赵成刚-我的-设置
-->
<template>
  <view class="mysetting-box">
    <view class="settingList-box">
      <view
        v-for="(item, index) in settingList"
        :key="index"
        class="item-box"
        @click="clickBtn(item)">
        <p>
          <view>
            {{ item.name }}
          </view>
          <view
            v-if="item.type == 2 && showVersionnumber"
            class="m-li-title"></view>
        </p>
        <p class="currentSize-box">
          <view v-if="item.type == 1">
            {{ currentSize ? currentSize : '' }}
          </view>
          <u-switch
            v-if="item.type == 4"
            @change="handleChangeSwitch"
            v-model="voiceChecked"></u-switch>
          <u-icon
            v-else
            name="arrow-right"></u-icon>
        </p>
      </view>
    </view>
    <view>
      <p class="versionnumber-box">当前版本号:v{{ versionnumber }}</p>
      <template v-if="userAccount && Object.keys(userInfo).length != 0">
        <u-button
          type="primary"
          @click="handleClickLogout"
          >退出登录
        </u-button>
      </template>
    </view>
    <u-toast ref="uToast" />
    <!-- 退出二次确认弹窗 -->
    <outmodal
      @cancel="handleOutmodalCancel"
      @submit="handleOutmodalSubmit"
      v-if="showOutmodalModal" />
    <loginTip
      :loginTipShow="loginTipShow"
      @confirm="loginTipConfirm"
      @cancel="loginTipCancel" />
    <certificateTip
      :certificateTipShow="certificateTipShow"
      @confirm="certificateTipConfirm"
      @cancel="certificateTipCancel"
      desc="通过审核后即可设置账户密码" />
  </view>
</template>
<script>
import outmodal from './outmodal.vue'
import { mapMutations } from 'vuex'
import loginTip from '../../../../components/C_tipModal/loginTip.vue'
import certificateTip from '../../../../components/C_tipModal/certificateTip.vue'
export default {
  name: 'mysetting',
  components: { outmodal, loginTip, certificateTip },
  data() {
    return {
      loginTipShow: false,
      certificateTipShow: false,
      settingList: [
        {
          name: '修改密码',
          type: 3,
          path: '/pages/login/editpassword'
        },
        {
          name: '设置账户密码',
          type: 3,
          path: '/pages/bank/pwd'
        },
        {
          name: '账号注销',
          type: 3,
          path: '/pages/login/accountcancellation'
        },
        {
          name: '隐私政策',
          type: 3,
          path: '/pages/drivertabbar/my/mysetting/privacypolicy'
        },
        {
          name: '清除缓存',
          type: 1
        },
        {
          name: '关于我们',
          type: 3,
          path: '/pages/login/aboutus'
        }
      ],
      versionnumber: '1.0.0',
      showVersionnumber: false,
      versionnumberObj: {},
      currentSize: '',
      downloadNum: '',
      showdownLine: '',
      showOutmodalModal: false,
      userAccount: {},
      userInfo: null,
      voiceChecked: true
    }
  },
  onLoad() {
    this.getStorageSize()
    this.voiceChecked = uni.getStorageSync('voiceChecked')
  },
  onShow() {
    this.userInfo = uni.getStorageSync('userInfo')
    this.settingList[1].name = `${
      this.userInfo.operatePwdFlag == '0' || !this.userInfo ? '设置' : '修改'
    }账户密码`
    this.userAccount = uni.getStorageSync('userAccount')
  },
  methods: {
    handleChangeSwitch(e) {
      this.voiceChecked = e
      uni.setStorageSync('voiceChecked', e)
    },
    certificateTipConfirm() {
      this.certificateTipShow = false
    },
    certificateTipCancel() {
      this.certificateTipShow = false
    },
    loginTipConfirm() {
      this.loginTipShow = false
    },
    loginTipCancel() {
      this.loginTipShow = false
    },
    // 获取本地缓存大小
    getStorageSize() {
      let that = this
      // #ifdef APP-PLUS
      plus.cache.calculate(function (size) {
        let sizeCache = parseInt(size)
        if (sizeCache == 0) {
          that.currentSize = '0B'
        } else if (sizeCache < 1024) {
          that.currentSize = sizeCache + 'B'
        } else if (sizeCache < 1048576) {
          that.currentSize = (sizeCache / 1024).toFixed(2) + 'KB'
        } else if (sizeCache < 1073741824) {
          that.currentSize = (sizeCache / 1048576).toFixed(2) + 'MB'
        } else {
          that.currentSize = (sizeCache / 1073741824).toFixed(2) + 'GB'
        }
      })
      plus.runtime.getProperty(plus.runtime.appid, (info) => {
        that.versionnumber = info.version
      })
      // #endif
      this.androidUpdate()
    },
    // 清理缓存
    clearStorage() {
      let that = this
      // #ifdef APP-PLUS
      let os = plus.os.name
      if (os == 'Android') {
        let main = plus.android.runtimeMainActivity()
        let sdRoot = main.getCacheDir()
        let files = plus.android.invoke(sdRoot, 'listFiles')
        let len = files.length
        console.log(files, len)
        for (let i = 0; i < len; i++) {
          let filePath = '' + files[i] // 没有找到合适的方法获取路径，这样写可以转成文件路径
          plus.io.resolveLocalFileSystemURL(
            filePath,
            function (entry) {
              if (entry.isDirectory) {
                entry.removeRecursively(
                  function (entry) {
                    //递归删除其下的所有文件及子目录
                    that.files = []
                    uni.showToast({
                      title: '清除成功',
                      duration: 2000
                    })
                    that.getStorageSize() // 重新计算缓存
                  },
                  function (e) {
                    console.log(e.message)
                  }
                )
              } else {
                entry.remove()
              }
            },
            function (e) {
              console.log('文件路径读取失败')
            }
          )
        }
      } else {
        // ios
        plus.cache.clear(function () {
          uni.showToast({
            title: '清除成功',
            duration: 2000
          })
          that.getStorageSize()
        })
      }
      // #endif
    },
    clickBtn(val) {
      if (
        (val.name == '修改密码' ||
          val.name == '账号注销' ||
          val.name == '设置账户密码' ||
          val.name == '修改账户密码') &&
        !this.userInfo
      ) {
        return (this.loginTipShow = true)
      }
      if (
        (val.name == '设置账户密码' || val.name == '修改账户密码') &&
        this.userInfo.authStatus == '0'
      ) {
        return (this.certificateTipShow = true)
      }
      switch (val.type) {
        case 1:
          this.clearStorage()
          break
        case 2:
          this.checkUpdates(this.versionnumberObj)
          break
        default:
          uni.navigateTo({
            url: val.path
          })
          break
      }
    },
    ...mapMutations(['logout']),
    handleClickLogout() {
      this.showOutmodalModal = true
    },
    handleOutmodalCancel() {
      this.showOutmodalModal = false
    },
    handleOutmodalSubmit() {
      this.showOutmodalModal = false
      this.tokenLogout()
    },
    // 检测版本更新
    checkUpdates(val) {
      // 待更新版本
      const currentVersion = val.versionNo
      // 更新地址
      let androidUrl = val.installationPackageUrl
      // 是否强制更新 isMust 0.否 1.强制更新
      let showCancel = val.isMust ? true : false
      //  比较版本是否不同 当前版本：plus.runtime.version
      const localVersion = this.versionnumber.split('.')
      let current = currentVersion.split('.')
      // 默认是同一个版本，不需要更新
      let flag = false
      current.forEach((item, i) => {
        if (item !== localVersion[i]) {
          // 检测到版本不同，需要更新
          flag = true
        }
      })

      if (flag) {
        uni.showModal({
          // 更新提醒
          title: '发现新版本，是否更新',
          content: '待更新版本号：' + currentVersion,
          success: (res) => {
            if (res.confirm) {
              this.doUpData(androidUrl)
              this.showdownLine = true
            } else if (res.cancel) {
              // 不更新强制退出app
              if (showCancel) {
                // #ifdef APP-PLUS
                plus.runtime.quit()
                // #endif
              }
            }
          }
        })
      } else {
        this.$u.toast('当前已是最新版本')
      }
    },
    doUpData(Url) {
      uni.showLoading({
        title: '更新中……'
      })
      const downloadTask = uni.downloadFile({
        //执行下载
        url: Url, //下载地址
        timeout: 1000 * 30, //30秒超时时间
        success: (downloadResult) => {
          //下载成功
          this.showdownLine = false
          uni.hideLoading()
          if (downloadResult.statusCode == 200) {
            // #ifdef APP-PLUS
            plus.runtime.install(
              //安装软件
              downloadResult.tempFilePath,
              {
                force: true
              },
              function (res) {
                plus.runtime.restart()
              }
            )
            // #endif
          }
        },
        fail: (err) => {
          uni.hideLoading()
          this.showdownLine = false
          this.$u.toast(err.errMsg)
          console.log(err)
        },
        complete: (com) => {
          console.log(com)
        }
      })

      // 下载进度
      downloadTask.onProgressUpdate((res) => {
        // this.$u.toast(res.progress)
        this.downloadNum = res.progress
        // console.log('下载进度' + res.progress);
        // console.log('已经下载的数据长度' + res.totalBytesWritten);
        // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);

        // 满足测试条件，取消下载任务。
        // if (res.progress > 50) {
        // 	downloadTask.abort();
        // }
      })
    },
    async androidUpdate() {
      //调用接口获取后台版本信息，检查是否需要更新
      const { code, result, message } = await this.$u.get(
        '/freight-auth/version/queryVersion',
        { packageType: 2 }
      )
      if (code == '0') {
        this.versionnumberObj = result
        const localVersion = this.versionnumber.split('.')
        let current = result.versionNo.split('.')
        // 默认是同一个版本，不需要更新
        let flag = false
        current.forEach((item, i) => {
          if (item !== localVersion[i]) {
            // 检测到版本不同，需要更新
            flag = true
          }
        })
        if (flag) {
          this.showVersionnumber = true
        } else {
          this.showVersionnumber = false
        }
      } else {
        this.$api.msg(message)
      }
    },
    //调用退出接口
    async tokenLogout() {
      const { code, result, message } = await this.$u.get(
        '/freight-auth/token/logout'
      )
      if (code === '0') {
        this.logout()
        // // #ifdef APP-PLUS
        // plus.runtime.quit()
        // // #endif
      } else {
        this.$api.msg(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.mysetting-box {
  height: 100vh;
  background: #f6f6f6;
  padding: 24rpx 30rpx 40rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .settingList-box {
    background: #fff;
    border-radius: 10rpx;
  }
  .item-box {
    display: flex;
    justify-content: space-between;
    line-height: 80rpx;
    padding: 4rpx 20rpx;
    margin: 0 4rpx 4rpx 4rpx;
    border-top: 2rpx solid #e5e5e5;
    .currentSize-box {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
    }
    p {
      display: flex;
    }
    .m-li-title {
      position: relative;
      margin-left: 6rpx;
      &::after {
        content: '';
        position: absolute;
        right: -7rpx;
        top: 28rpx;
        width: 6rpx;
        height: 6rpx;
        background: #ff4d4f;
        border-radius: 10rpx;
      }
    }
  }
  .item-box:nth-child(1) {
    border: none;
  }
  .versionnumber-box {
    text-align: center;
    margin-top: 20rpx;
    margin-bottom: 60rpx;
    color: #999999;
  }
}
</style>
